package com.yjm.test.Spring5.ch3.autowire;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.context.support.GenericApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;
import org.springframework.stereotype.Component;

@Component("target")
@Lazy
public class Target {
	private Foo fooOne;
	private Foo fooTwo;
	private Bar bar;
	
	Target() {
		System.out.println("default constructor called!");
	}
	Target(Foo foo) {
		System.out.println("Target(Foo) constructor called!");
	}
	Target(Foo foo, Bar bar) {
		System.out.println("Target(Foo, Bar) constructor called!");
	}
	public Foo getFooOne() {
		return fooOne;
	}
	@Autowired
	public void setFooOne(Foo fooOne) {
		this.fooOne = fooOne;
		System.out.println("property fooOne set:" + fooOne.getName());
	}
	public Foo getFooTwo() {
		return fooTwo;
	}
	@Autowired
	@Qualifier("fooTwo")
	public void setFooTwo(Foo fooTwo) {
		this.fooTwo = fooTwo;
		System.out.println("property fooTwo set:" + fooTwo.getName());
	}
	public Bar getBar() {
		return bar;
	}
	@Autowired
	public void setBar(Bar bar) {
		this.bar = bar;
		System.out.println("property Bar set:" + bar.getName());
	}
	
	
	public static void testXml() {
		GenericXmlApplicationContext ctx = new GenericXmlApplicationContext();
		ctx.load("classpath:spring/ch3/autowire.xml");
		ctx.refresh();
		
		Target t = null;
		System.out.println("Using byName:");
		t = (Target) ctx.getBean("targetByName");
		
		System.out.println("Using ByType:");
		t = (Target) ctx.getBean("targetByType");
		
		System.out.println("Using constructor:");
		t = (Target) ctx.getBean("targetConstructor");
		
		ctx.close();
	}
	
	@Configuration
	@ComponentScan(basePackages="com.yjm.test.Spring5.ch3.autowire")
	public static class AnnotationConfiguration {
		
	}
	
	public static void testAnnotation() {
		GenericApplicationContext ctx = new AnnotationConfigApplicationContext(AnnotationConfiguration.class);
		//ctx.refresh();
		
		Target t = null;
		System.out.println("Annotation Using byType default:");
		t = (Target) ctx.getBean("target");
		
		ctx.close();
	}
	
	public static void main(String... args) {
		testAnnotation();
		testXml();
	}
}
